package com.permission.systempermission.controller.sysManagement;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.permission.systempermission.comm.Result.ResultVo;
import com.permission.systempermission.model.User;
import com.permission.systempermission.service.IUserService;
import com.permission.systempermission.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kappy
 * @since 2025-11-18
 */
@RestController
@RequestMapping("/sys")
@Api(value = "User", tags = "用户管理-用户业务操作服务接口", description = "用户管理-用户业务操作服务接口")    //模块接口名称
public class UserController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "用户登录接口")
    public ResultVo login(@RequestBody User user) {
        try {
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
            // 2. 执行认证,同时会执行loadUserByUsername方法
            Authentication authentication = authenticationManager.authenticate(authToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            //生成token验证
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", auth.getName());
            User sysUser = userService.getOne(queryWrapper);
            Map map = new HashMap<>();
            map.put("token", JwtUtils.createJWT(JSON.toJSONString(sysUser.getUserId()), user.getUserName(), 1000 * 60*30));
            map.put("user", sysUser);
            return ResultVo.success("的", map);
        } catch (BadCredentialsException e) {
            return ResultVo.success("密码错误，请重新输入!");
        } catch (AuthenticationException e) {
            return ResultVo.success(e.getMessage());
        }
    }
}
